﻿using Newtonsoft.Json;
using PIMS.DBModel;
using PIMS.WorkPlugin.EAS;
using PIMS.WorkPlugin.ORM;
using PIMS.WorkPlugin.Util.Config;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;
using System.Windows.Forms;

namespace PIMS.YongXiang
{
    public class EASHelper
    {
        /// <summary>
        /// RSA密钥对 调试环境
        /// </summary>
        private static string pubKeyDebug = "<RSAKeyValue><Modulus>nwzv7mA2s+6qHrSLllLN4/iEkr7zTzXu7mS5nqadrefwl9QymeldfRaKyn6oQy6LaLEJXLl+oK3vwA6qdj0EGC5FLIgwqlBWzRVyuKhT9/ojEUPvT3fLOy2pHu75H2geWVXUGEkWpaciiR/ZAusBCXQJ9+HZ2A2IudHXJvoIJD8=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        private static string priKeyDebug = "<RSAKeyValue><Modulus>nwzv7mA2s+6qHrSLllLN4/iEkr7zTzXu7mS5nqadrefwl9QymeldfRaKyn6oQy6LaLEJXLl+oK3vwA6qdj0EGC5FLIgwqlBWzRVyuKhT9/ojEUPvT3fLOy2pHu75H2geWVXUGEkWpaciiR/ZAusBCXQJ9+HZ2A2IudHXJvoIJD8=</Modulus><Exponent>AQAB</Exponent><P>7KAW2jsvmTZVAkKo0VzWtUwbtQIf/NtS8YiI1aJ37poXBXfF+kRD7kBzI+/0wFOATqlf4x4u7gKJvzMgLFmo/Q==</P><Q>rBLM0oFcOLVwF9jCWOmo+jvYC2iOIXol9IG6poMU7ot9BvrNxb1Fjq/3MH0GAceSaqeoXoGmb2SrZo/0u5NU6w==</Q><DP>Ii11X4wQ8fZRDQSH0cWxFXqqvdhSunkLX+uyp/jRjdsf3CBSrjVSAoW4m8Y6+dSVwcbhHLLtYF9pef5udTl2GQ==</DP><DQ>DI46n8mMnx6uFS9dzvsNt2SSeRKh/FNbXaHxqqC58EYBU3cNeLY80xKH6OPWgl67kki1gl/Xcx1XXF54rw8rDQ==</DQ><InverseQ>YjVAMvtsf0arBOYqz9SLJCGMSEVSJsa12DJLJ209wt0h1zacscLxnApmuPtEqyKgL7BTKrqP9U6/SXAKOvTUcA==</InverseQ><D>L7NKlfxHC6mtXa4aGwhUdWWIJRadlAkB0n9k5/7iVVC1aGOclWpWvngvQdHAlv1zk/9cZnG/V2My/y+m0fU0r61GBRHD/o09flRT94qxcX02jiBue5F/7rdaHkiOyWlieJCsbXpLWXoSNAggK0ZQybFwW3V7UGkQdGDDWDQT7mk=</D></RSAKeyValue>";
        
        /// <summary>
        /// RSA密钥对 正式环境
        /// </summary>
        private static string pubKey = "<RSAKeyValue><Modulus>3CmUXKkO6aMgiAddbzvFrT3lUma25U8aFTfXKsqbcggSIVJqk0ZkRq7j0gMVXLJnpcl3pZ/Cl41cA4Gbg0+C02jAD/c+I8dQ0DbV3UGcka3g79k+uekaSKIuf0OulMJs3ngzizSMCwX+WZlR1dChMTvScEk+MId+rGZib8CMzo0=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
        private static string priKey = "<RSAKeyValue><Modulus>3CmUXKkO6aMgiAddbzvFrT3lUma25U8aFTfXKsqbcggSIVJqk0ZkRq7j0gMVXLJnpcl3pZ/Cl41cA4Gbg0+C02jAD/c+I8dQ0DbV3UGcka3g79k+uekaSKIuf0OulMJs3ngzizSMCwX+WZlR1dChMTvScEk+MId+rGZib8CMzo0=</Modulus><Exponent>AQAB</Exponent><P>6T6GXQPrW9dHwNfcwbEN/0tnOY2DpJ8ZkSrJxkuEWwWFKd9L3vDOiEsinqXwfUi7Lw89VaiSKoTSgB9UU/5FIw==</P><Q>8aRTNpmwq3ZGAgGqP+vHfscJVCbIWyb9nDagj7RAljaIeZ4sXGEeCy3pnbuqG/sjEZmdT2UMGXrs/uZMeiYQjw==</Q><DP>Q+tdHQDjLF9IGbPCKPTx6oF+kZfP2cQqoccf8opTBF5bJJJNeaINwkp+zkvr98+SEmYRqjvoNFFxKrX0zHCimQ==</DP><DQ>Csu8rAPR0NdH6W8JnDF8iD18PTY+XVQwoHoQUltLR2rITiay9K2iGf3DIjjwMK/XsUGbtaBeGgVT8U94uzxYIQ==</DQ><InverseQ>h32N+aI5DAZDrhbMnlSYJx8Wg/XU5gPefIYsZX6SflpL26wQqa4M3vkceOwC601mvyah+MmEJaZmGu57cwZg3A==</InverseQ><D>VFml2v52lTMHorZXqOdYrDA7rR9nUWHGF30GdgGcHstSzut5o6Vjg+U7qdm+lH5R0aXnrlAQSOpC56D/iQask0bsCwuOlJQPa6Vud0kb3OjgD8tMZSHxPOWIMU2DHWIDdu8YNxq/lqy/v80syTNEESfjXc7DQTaU6YUW/L7JIg0=</D></RSAKeyValue>";
        private static string apiUrl = ConfigManager.AppSettings["easurl"].Value;
        private static string Uid = "123";
        private static string batchHead= ConfigManager.AppSettings["batchHead"].Value;
		private static string batchNotHead= ConfigManager.AppSettings["batchNotHead"].Value;


		private static string PrivateKey
        {
            get
            {
                if (apiUrl.EndsWith("Debug"))
                {
                    return priKeyDebug;
                }
                return priKey;
            }
        }
        private static string PublicKey
        {
            get
            {
                if (apiUrl.EndsWith("Debug"))
                {
                    return pubKeyDebug;
                }
                return pubKey;
            }
        }

        /// <summary>
        /// 2.38 获取包装批号接口
        /// </summary>
        /// "[{\"PACKAGENUMBER\":\"YX-A-24-210701/S4/致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S2/致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S3/YX03致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S2/YX03致密料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S2/疏松料/围板箱/方硅芯\"},{\"PACKAGENUMBER\":\"YX-A-24-210701/S3/致密料/围板箱/方硅芯\"}]"
        /// 无结果返回 []
        /// <param name="manufactureBatch">生产批号</param>
        public static string GetPackageBatch(string manufactureBatch = "YX-A-24-210701")
        {
            try
            {
                string action = "{\"fun\":\"GetPackageBatch\",\"prms\":{\"manufacturebatch\":\"" + manufactureBatch + "\"}}";
                string uid = "123";
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                string result = HttpPost(header, apiUrl, action);
                return result;
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value, "Ex");
                }
            }
            catch (Exception ex)
            {
                Exception src = ex.GetBaseException();
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
            return null;
        }

        /// <summary>
        /// 2.40 上传箱号信息
        /// </summary>
        /// "{\"msg\":\"\",\"data\":{},\"flage\":1}"
        /// 
        /// "{\"msg\":\"错误:null\\nCaused exception message is: JSONObject[\\\"detail\\\"] is not a JSONArray.\",\"flage\":0}"
        /// "{\"msg\":\"错误:null\\nCaused exception message is: null object\",\"flage\":0}"
        /// "{\"msg\":\"错误:null\\nCaused exception message is: 该箱号:X2C12021090001已存在!不能重复导入!\",\"flage\":0}"
        public static string Import_CartonInfo(string boxId)
        {
            string packtype = "";
            CartonInfo cartonInfo = new CartonInfo();
            //能源科技公司编码YX.10.20
            //云南通威二期公司编码YX.10.22
            //内蒙通威硅能源公司编码YX.10.21
            cartonInfo.company = "YX.10.11";
            cartonInfo.billbizdate = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            cartonInfo.cartonNumber = boxId;  //X2C12021090004
            cartonInfo.lot = "t1"; //未确定要不要
            cartonInfo.packageline = ""; //非必填
            cartonInfo.detail = new List<string>();
            

            try
            {
                DataTable dtBox= SqlSugarHelper.QueryToDataTable<saveddata>(
                    string.Format("select * from tb_saveddata where uid='{0}'",boxId));
                DataTable dtBag = SqlSugarHelper.QueryToDataTable<saveddataBag>(
                    string.Format("select * from tb_saveddataBag where boxid='{0}'", boxId));

                if (dtBox.Rows.Count > 0)
                {
                    cartonInfo.carNumber = dtBox.Rows[0]["reserved6"].ToString().Trim(); //车号
                    if (string.IsNullOrEmpty(dtBox.Rows[0]["reserved2"].ToString().Trim())) //定制料信息
                        cartonInfo.specialInfo = dtBox.Rows[0]["reserved3"].ToString().Trim(); //客户单位
                    else
                        cartonInfo.specialInfo = dtBox.Rows[0]["reserved2"].ToString().Trim() + ";" //定制料信息
                                + dtBox.Rows[0]["reserved3"].ToString().Trim(); //客户单位
                    cartonInfo.materialcase = dtBox.Rows[0]["productName"].ToString().Trim().Replace("（", "(").Replace("）", ")").Replace(" ", ""); //型号
                    cartonInfo.material = dtBox.Rows[0]["reserved11"].ToString().Trim(); //物料编码
                    cartonInfo.particleSize = dtBox.Rows[0]["productMark"].ToString().Trim(); //粒径
                    cartonInfo.grossWeight = dtBox.Rows[0]["reserved1"].ToString().Trim(); //毛重 要求纯数字
                    cartonInfo.netWeight = dtBox.Rows[0]["weight"].ToString().Trim(); //净重 要求纯数字
                    cartonInfo.manufacturebatch = dtBox.Rows[0]["batchNo"].ToString().Trim(); //批号
                    cartonInfo.packageNumber = dtBox.Rows[0]["reserved5"].ToString().Trim(); //包装批次

                    if (cartonInfo.packageNumber.Contains("纸箱"))
                        cartonInfo.packageType = 1;
                    else if (cartonInfo.packageNumber.Contains("围板箱"))
                        cartonInfo.packageType = 2;
                    else
                        cartonInfo.packageType = 0;

                    string[] strings = cartonInfo.packageNumber.Split('/');
                    if (5 == strings.Length)
                    {
                        packtype = strings[4] + "/" + strings[5];
                    }

                    if (dtBox.Rows[0]["reserved7"].ToString().Trim() == "1") //上传EAS标志
                    {
                        return "Err:" + "重复上传!" + boxId;
                    }
                }
                else
                {
                    return "Err:" + "数据库中没有此箱标的记录!" + boxId;
                }
                if (dtBag.Rows.Count > 0)
                {
                    for (int i = 0; i < dtBag.Rows.Count; i++)
                    {
                        cartonInfo.detail.Add(dtBag.Rows[i]["uid"].ToString().Trim()); //袋标
                    }
                }
                else
                {
                    return "Err:" + "数据库中此箱标绑定的袋标记录!" + boxId;
                }
            }
            catch (Exception ex)
            {
                if(ex.Message.Contains("已存在!不能重复导入"))
                {
                    SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}'", boxId),
                      new Dictionary<string, object>() { { "reserved7", "1" },{ "reserved10",packtype} }); //上传EAS标志
                }
                return "Err:" + ex.Message;
            }

            try
            {
                string para = JsonConvert.SerializeObject(cartonInfo);
                string action = "{\"fun\":\"Import_CartonInfo\",\"prms\":" + para + "}";
                string result = HttpPostAction(action);

                Result r = JsonConvert.DeserializeObject<Result>(result.Replace("\"{", "{").Replace("\\\"", "\"").Replace("}\"", "}"));
                if (r.flage == 1)
                {
                    SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}'", boxId),
                       new Dictionary<string, object>() { { "reserved7", "1" } }); //上传EAS标志
                }
                else
                {
                    return "Err:" + r.msg;
                }
                JavaScriptSerializer jss = new JavaScriptSerializer();
                return jss.Serialize(r);
            }
            catch (Exception ex)
            {
                return "Err:" + ex.Message;
            }
        }

        /// <summary>
        /// 2.46 获取箱号信息
        /// </summary>
        /// <param name="cartonNumber"></param>
        public static string GetCartonInfo(string param,string value, out CartonHistory carton)
        {
            carton = null;
            try
            {
                string action = "{\"fun\":\"GetCartonInfo\",\"prms\":{\"" + param + "\":\"" + value + "\"}}";
                string result = HttpPostAction(action);
                
                try
                {
                    CartonHistory[] r = JsonConvert.DeserializeObject<CartonHistory[]>(result);
                    if (r.Length > 0)
                    {
                        carton = r[0];
                        if (param.Equals("cartonNumber"))
                        {
                            DataTable dtBox = SqlSugarHelper.QueryToDataTable<saveddata>(
                                string.Format("select * from tb_saveddata where uid='{0}'", carton.CARTONNUMBER));

                            if (dtBox.Rows.Count == 0)
                            {
                                saveddata boxManual = new saveddata();
                                boxManual.uid = carton.CARTONNUMBER;
                                boxManual.packager = "0";
                                boxManual.workOrder = DateTime.Now.ToString("yyMMddHHmmss");
                                boxManual.batchNo = carton.MANUFACTUREBATCH;
                                boxManual.productName = carton.MATERIALNAME;
                                boxManual.productMark = carton.PARTICLSIZE;
                                boxManual.weight = carton.NETWEIGHT.ToString();
                                boxManual.reserved1 = carton.GROSSWEIGHT.ToString();
                                if (null != carton.SPEICIALINFO)
                                    boxManual.reserved3 = carton.SPEICIALINFO.ToString();
                                boxManual.reserved5 = carton.PACKAGENUMBER;
                                boxManual.reserved8 = carton.BILLSTATUS;
                                boxManual.reserved10 = carton.MATERIALCASEREMA;
                                boxManual.reserved11 = carton.MATERIALNUMBER;
                                boxManual.productTime = carton.PACKAGEDATE;
                                if (0 >= SqlSugarHelper.InsertRecord(boxManual))
                                    return "Err:人工箱插入数据库失败!!!";
                            }
                            else if (carton.CARTONNUMBER.Trim().Length == 15)
                            {
                                SqlSugarHelper.UpdateRecord<saveddata>(string.Format("uid='{0}'", carton.CARTONNUMBER),
                                        new Dictionary<string, object>() { { "reserved10", carton.MATERIALCASEREMA } });
                            }
                        }
                        return "";
                    }
                    else
                        return "Err:未找到箱号信息!!!箱号:" + value;
                }
                catch(Exception err)
                {
                    return "Err:" + err.Message + "\r\n" + result;
                }
                
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string data = reader.ReadToEnd();
                    // MessageBox.Show(value, "Ex");
                    return "Err:" + data;
                }
                return "Err:网络错误"; 
            }
            catch (Exception ex)
            {
                Exception src = ex.GetBaseException();
                return "Err:" + ex.Message + ex.StackTrace;
            }
        }

        /// <summary>
        /// 2.28.	托码回传接口（Import_CpRelation）
        /// </summary>
        public static string Import_CpRelation(string[] cartonNumbers,string palletNumber)
        {
            try
            {
                Palletbject palletbject = new Palletbject();
                palletbject.palletNumber = palletNumber;
                palletbject.entries = cartonNumbers;

                string para = JsonConvert.SerializeObject(palletbject);
                string action = "{\"fun\":\"Import_CpRelation\",\"prms\":" + para + "}";
                string result = HttpPostAction(action);

                Result r = JsonConvert.DeserializeObject<Result>(result.Replace("\"{", "{").Replace("\\\"", "\"").Replace("}\"", "}"));
                if (r.flage == 1)
                {
                    SqlSugarHelper.UpdateRecord<saveddata>(String.Format("uid='{0}' or uid='{1}'", cartonNumbers[0], cartonNumbers[1]),
                       new Dictionary<string, object>() { { "reserved15", "1" },{ "reserved20", palletNumber} }); //上传EAS标志
                }
                else
                {
                    return "Err:" + r.msg;
                }
                //JavaScriptSerializer jss = new JavaScriptSerializer();
                return "";//jss.Serialize(r);
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value, "Ex");
                }
            }
            catch (Exception ex)
            {
                return ex.Message + ex.StackTrace;
            }
            return "";
        }

        public class Rootobject
        {
            public string fun { get; set; }
            public Prms prms { get; set; }
        }
        public class Prms
        {
            public string carNumber { get; set; }
        }
        public class RootBatchInfo
        {
            public string FNUMBER { get; set; }
            public int CFBATCHTYPE { get; set; }
            public string FCREATETIME { get; set; }
        }
        /// <summary>
        /// 获取生产批次
        /// </summary>
        public static void GetManufacturebatch()
        {
            Rootobject root = new Rootobject();
            root.fun = "GetManufacturebatch";
            root.prms = new Prms();
            root.prms.carNumber = "";
            string action = JsonConvert.SerializeObject(root);
            //SQLLog.DBLog(action);
            try
            {
                string result = HttpPostAction(action);
                result = result.Replace("\\", "").
                                Replace("\"[", "[").
                                Replace("]\"", "]").
                                Replace("\"null\"", "");
                List<RootBatchInfo> carInfo = JsonConvert.DeserializeObject<List<RootBatchInfo>>(result);
                int nSysCount = 0;
                foreach (var item in carInfo)
                {
                    //if ( /*1 == item.CFBATCHTYPE ||*/ item.FNUMBER.StartsWith("YT-A") || item.FNUMBER.StartsWith("YN-B") || item.FNUMBER.StartsWith("YN-C")
                    //    || item.FNUMBER.StartsWith("YN-D") || item.FNUMBER.StartsWith("YNH"))
                    if (FilterBatchNo(item.FNUMBER, batchHead) && (String.IsNullOrEmpty(batchNotHead) || 
                        (!String.IsNullOrEmpty(batchNotHead) && !FilterBatchNo(item.FNUMBER, batchNotHead))))
                    {
                        int nRet = 0;
                        //string strRet = string.Format("if  not exists (select * from EASBatch  where Batch='{0}') Insert Into EASBatch (Batch,[type],CreateAt) Values('{1}',{2},'{3}')",
                        //                        item.FNUMBER,
                        //                        item.FNUMBER,
                        //                        item.CFBATCHTYPE,
                        //                        item.FCREATETIME);
                        //int nRet = DbHelperSQL.ExecuteSql(strRet);
                        EASBatch easBatch = SqlSugarHelper.Query<EASBatch>(
                            String.Format("Batch='{0}'", item.FNUMBER), "CreateAt");
                        if (easBatch == null) 
                        {
                            easBatch = new EASBatch();
                            easBatch.Batch = item.FNUMBER;
                            easBatch.type = item.CFBATCHTYPE.ToString();
                            easBatch.CreateAt = item.FCREATETIME;
                            nRet=SqlSugarHelper.InsertRecord<EASBatch>(easBatch);
                        }
                        if (nRet > 0)
                            nSysCount++;
                    }
                }
               // return string.Format("查到{0}条记录,已同步", nSysCount);
            }
            catch (Exception ex)
            {
                throw ex;
               // return "Err:" + ex.Message;
            }
        }

        private static bool FilterBatchNo(string batchNo,string filterStr)
        {
            if(String.IsNullOrEmpty(filterStr))
            {
				return true;
			}             
            else
            {
				if(filterStr.Contains("|"))
                {
                    string[] strs = filterStr.Split('|');
                    foreach(string s in strs)
                    {
                        if(batchNo.Contains(s))
                        {
							return true;
						}
                    }

				}
                else
                {
					if (batchNo.Contains(filterStr))
					{
						return true;
					}
				}
			}
			return false;
		}

        public static void Test()
        {
            try
            {
                string action = "{\"fun\":\"ApiTest\",\"prms\":[]}";
                string uid = "123";
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                //timespan = 1594883862103;
                //token = "";
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                string result = HttpPost(header, apiUrl, action);
                MessageBox.Show(result,"ok");
            }
            catch (WebException we)
            {
                if (we.Response != null)
                {
                    Stream stream = we.Response.GetResponseStream();
                    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                    string value = reader.ReadToEnd();
                    MessageBox.Show(value,"Ex");
                }
            }
            catch (Exception ex)
            {
                Exception src = ex.GetBaseException();
                MessageBox.Show(ex.Message + ex.StackTrace);
            }
        }

        private static string GetToken()
        {
            string action = "{\"fun\":\"GetToken\",\"prms\":{}}";
            string uid = "123";
            string token = "";
            // 时间搓
            TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            long timespan = Convert.ToInt64(ts.TotalSeconds);
            string orgdata = action + uid + timespan + token;

            // 获取hash码
            string sign = RSAHelper.XMLSign(orgdata, PrivateKey);

            Dictionary<string, string> header = new Dictionary<string, string>();
            header.Add("uid", uid);
            header.Add("token", token);
            header.Add("timespan", timespan.ToString());
            header.Add("sign", sign);
            string result = HttpPost(header, apiUrl, action);
            result = RSAHelper.XMLRSADecrypt(PrivateKey, result.Trim('\"'));
            Console.WriteLine("Token:" + result);
            return result;
        }

        /// 后台发送POST请求
        /// <summary>
        /// <param name="url">服务器地址</param>
        /// <param name="data">发送的数据</param>
        /// <returns></returns>
        private static string HttpPost(Dictionary<string, string> header, string url, string data)
        {
            //创建post请求
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            request.Proxy = null;
            request.Method = "POST";
            foreach (string key in header.Keys)
            {
                request.Headers.Add(key, header[key]);
            }
            request.ContentType = "application/json;charset=UTF-8";
            byte[] payload = Encoding.UTF8.GetBytes(data);
            request.ContentLength = payload.Length;

            //发送post的请求
            Stream writer = request.GetRequestStream();
            writer.Write(payload, 0, payload.Length);
            writer.Close();

            //接受返回来的数据
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader reader = new StreamReader(stream, Encoding.UTF8);
            string value = reader.ReadToEnd();
            //string value = GetResponseStringJson((HttpWebResponse)request.GetResponse());

            reader.Close();
            stream.Close();
            response.Close();

            return value;
        }
        
        public static string HttpPostAction(string action)
        {
            try
            {
                string uid = Uid;
                string token = GetToken();

                // 时间搓
                TimeSpan ts = DateTime.Now - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                long timespan = Convert.ToInt64(ts.TotalSeconds);
                string orgdata = action + uid + timespan + token;

                // 获取hash码
                string sign = RSAHelper.XMLSign(orgdata, PrivateKey);
                Dictionary<string, string> header = new Dictionary<string, string>();
                header.Add("uid", uid);
                header.Add("token", token);
                header.Add("timespan", timespan.ToString());
                header.Add("sign", sign);
                string result = HttpPost(header, apiUrl, action);
                return result;
            }
            catch (WebException we)
            {
                //if (we.Response != null)
                //{
                //    Stream stream = we.Response.GetResponseStream();
                //    StreamReader reader = new StreamReader(stream, Encoding.UTF8);
                //    string value = reader.ReadToEnd();
                //    //MessageBox.Show(value, "Ex");
                //    return value;
                //}
                throw we;
            }
            catch (Exception ex)
            {
                // Exception src = ex.GetBaseException();
                // MessageBox.Show(ex.Message + ex.StackTrace);
                //return ex.Message;
                throw ex;
            }
        }

        /// <summary>  
        /// 返回List集合对象  
        /// </summary>  
        /// <typeparam name="T"></typeparam>  
        /// <param name="JsonStr"></param>  
        /// <returns></returns>  
        public static List<T> JSONStringToList<T>(string JsonStr)
        {
            //使用JavaScriptSerializer()方式转json，需要添加System.Web.Extensions.dll
            JavaScriptSerializer Serializer = new JavaScriptSerializer();
            List<T> objs = Serializer.Deserialize<List<T>>(JsonStr);
            return objs;
        }

        public static Code GetNewCode(string number)
        {
            Code code = new Code();
            code.number = number;
            return code;
        }

        public static string GetResponseStringJson(HttpWebResponse webResponse)
        {
            using (Stream s = webResponse.GetResponseStream())
            {
                StreamReader reader = new StreamReader(s, Encoding.UTF8);
                string resp = reader.ReadToEnd();//Regex.Unescape(resp);

                JsonReader readerJson = new JsonTextReader(new StringReader(resp)); //针对转义字符特殊处理
                while (readerJson.Read())
                {
                    resp = readerJson.Value.ToString();
                }
                readerJson.Close();
                reader.Close();
                return resp;
            }
        }
    }
}
